import time
import threading
from src.core import log
from typing import Dict, Optional


class DynamicThreadPool:
    def __init__(self):
        self.threads: Dict[str, threading.Thread] = {}
        self.stop_flags: Dict[str, threading.Event] = {}
        self.lock = threading.Lock()

    def start_thread(self, name: str, target: callable, *args, **kwargs) -> bool:
        """启动一个线程并加入管理"""
        # log.DEBUG(f"启动线程: {name}")
        with self.lock:
            if name in self.threads:
                log.DEBUG(f"线程{name}已存在！")
                return False  # 线程已存在

            stop_event = threading.Event()
            self.stop_flags[name] = stop_event

            def wrapped_target():
                while not stop_event.is_set():
                    target(*args, **kwargs)

            thread = threading.Thread(target=wrapped_target, name=name, daemon=True)
            self.threads[name] = thread
            thread.start()
            log.DEBUG(f"线程{name}启动成功！")
            return True

    def stop_thread(self, name: str) -> bool:
        """停止指定线程"""
        log.DEBUG(f"停止线程: {name}")
        with self.lock:
            if name not in self.threads:
                return False

            self.stop_flags[name].set()  # 设置停止标志
            self.threads[name].join()  # 等待线程结束

            del self.stop_flags[name]
            del self.threads[name]
            log.DEBUG(f"线程{name}停止成功！")
            return True

    def stop_all(self) -> None:
        """停止所有线程"""
        with self.lock:
            for name in list(self.threads.keys()):
                self.stop_thread(name)

    def get_thread_names(self) -> list:
        """获取所有线程名称"""
        with self.lock:
            return list(self.threads.keys())

    def thread_exists(self, name: str) -> bool:
        """检查线程是否存在"""
        with self.lock:
            return name in self.threads


tpoll = DynamicThreadPool()
